package com.example.edianzu.somur;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.api.constans.AppContents;
import com.example.edianzu.somur.api.manager.APIManager;
import com.example.edianzu.somur.login.mvp.view.LoginActivity;
import com.example.edianzu.somur.utils.content.ValidateUtils;
import com.example.edianzu.somur.utils.view.BaseActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class WelcomeActivity extends BaseActivity {

    private SharedPreferences sharedPreferences;
    private String phone;
    private String password;
    private String company_id;

    private static final int REQUEST_CODE_SETTING = 300;
    private final static int REQUEST_CODE_PERMISSION_MULTI=200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        隐藏StatusBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome);

        sharedPreferences =App.getApp().getSharedPreferences();

        //        Android 6.0权限申请
//        requestPermissions();

//        px转dp
//        Conversion.getDp();

//        判断是否是第二次登录
        phone = sharedPreferences.getString("phone","");
        password = sharedPreferences.getString("password", "");
        company_id = sharedPreferences.getString("company_id", "");

        if (!TextUtils.isEmpty(phone)&&!TextUtils.isEmpty(password)&&!TextUtils.isEmpty(company_id)) {

            checkLogin();
        }else {

            startActivity();
        }
    }

    private void requestPermissions() {

        AndPermission.with(getApplicationContext()).permission(
                Permission.LOCATION,
                Permission.STORAGE,
                Permission.PHONE)
                .requestCode(REQUEST_CODE_PERMISSION_MULTI)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {

                // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                AndPermission.rationaleDialog(WelcomeActivity.this, rationale).show();
            }
        }).callback(this).start();
    }

    @PermissionYes(REQUEST_CODE_PERMISSION_MULTI)
    private void getMultiYes(@NonNull List<String> grantedPermissions) {
        Toast.makeText(this, R.string.successfully, Toast.LENGTH_SHORT).show();
    }

    @PermissionNo(REQUEST_CODE_PERMISSION_MULTI)
    private void getMultiNo(@NonNull List<String> deniedPermissions) {
        Toast.makeText(this, R.string.failure, Toast.LENGTH_SHORT).show();

        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
                    .setTitle(R.string.title_dialog)
                    .setMessage(R.string.message_permission_failed)
                    .setPositiveButton(R.string.ok)
                    .setNegativeButton(R.string.no, null)
                    .show();

            // 更多自定dialog，请看上面。
        }
    }

    private void startActivity() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {

                startActivity(new Intent(WelcomeActivity.this,LoginActivity.class));
                finish();
            }
        },2*1000);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

//        startActivity();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    private void checkLogin() {

        if (password != null&& phone !=null) {
            if (phone.length()==11&& ValidateUtils.isMobileNO(phone)) {

                APIManager.getApiManagerInstance().getLoginInfo(new Observer<LoginInfo>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull LoginInfo loginInfo) {

                        if (loginInfo.getStatus()== AppContents.STATUS) {

//                    设置极光推送的tag
                            Set<String> tags= new HashSet<>();
                            tags.add(loginInfo.getData().getMember_id()+"");
                            JPushInterface.setTags(App.getApp().getApplicationContext(),1,tags);

                            Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                            intent.putExtra("member_id", loginInfo.getData().getMember_id());
                            intent.putExtra("login", loginInfo);

                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                        loginError();
                    }

                    @Override
                    public void onComplete() {

                    }
                },phone,password,company_id);
            }else {

                loginError();
            }
        }
    }

    private void loginError() {

        Toast.makeText(this, "网络异常请稍后再试！！！", Toast.LENGTH_SHORT).show();
    }
}
